package com.g9.blog.controller;

import com.g9.blog.common.Response;
import com.g9.blog.common.Result;
import com.g9.blog.entity.Users;
import com.g9.blog.service.impl.MyUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Auther: Graycat
 * @Date: 2020/9/8 15:23
 * Create by lwj.
 */

@Controller
public class MyUserController {
    
    @Autowired
    private MyUserServiceImpl userService;

    @GetMapping("/index")
    public String toUpload(  ){
        return "index";
    }

    // 新建用户--修改用户信息（id不同时新建，相同则修改）
    @PostMapping("/user")
    @ResponseBody
    public Result addUser(  Users users){
        userService.save(users);
        return Response.makeOKRsp("");
    }
    // 删除
    @DeleteMapping("/user/{userId}")
    @ResponseBody
    public Result deleteUser( @PathVariable int userId ){
        userService.deleteById(userId);
        return Response.makeOKRsp("删除成功。");
    }
    // 查找所有用户
    @GetMapping("/user")
    @ResponseBody
    public Result<List<Users>> getAllUser(){
        List<Users> usersList = userService.findAll();
        return Response.makeOKRsp(usersList);
    }
    // 查找某一用户--by username
    @GetMapping("/user/{username}")
    @ResponseBody
    public Result<List<Users>> getUserByName(@PathVariable String username ){
        List<Users> usersList = userService.findAllByUsername(username);
        if ( usersList !=null )
            return Response.makeOKRsp(usersList);
        return Response.makeErrRsp("无此用户！");
    }

    // 根据用户名上传用户图像并修改数据库的用户表-iron字段
    @PostMapping("/user/upload")
    @ResponseBody
    public Result upload( MultipartFile file , String username  ) {
        List<Users> userList = userService.findAllByUsername(username);
        Users theUse = userList.get(0);
        Result result = userService.updateUserIcon(file,theUse);
        return result;
    }
}
